import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/pages/member/entity/havelist_info_entity.dart';
import 'package:cbec_app/pages/member/entity/vip_card_item_entity.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/GlobalData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:get/get.dart';

///会员页控制器
class BaseCardMemberCtr extends BaseController with SingleGetTickerProviderMixin {
  HavelistInfoEntity? infoEntity;

  List<VipCardItemEntity> vipCardItems = [];

  // 标记当前卡位置
  int currentIndex = 0;

  /// 是否是已登录的请求
  bool isLogin = false;

  /// 当前卡对应的   购买卡的明细 列表
  List<VipCardItemBuyList> buyList = [];

  /// 标记 月，季 年，选中
  int selected = 0;

  /// 当前选中主卡
  VipCardItemEntity? currentMainCard;

  /// 当前选中次卡
  VipCardItemBuyList? currentSubCard;

  @override
  void onInit() {
    super.onInit();
    judgeFeatchData();

    ///监听路由
    EventMgr.on(EventType.refreshLogin, (arg) {
      judgeFeatchData();
    });
  }

  judgeFeatchData() {}

  ///获取用户可购买的权益卡列表
  Future getVipCanBuyCardListInfo() async {
    Tools.showLoading();
    var params = {'sid': AppData.sid};
    return Network.getVipCanBuyCardList(params).then((value) {
      vipCardItems = (value as List<dynamic>).map((item) {
        return VipCardItemEntity.fromJson(item as Map<String, dynamic>);
      }).toList();
      if (vipCardItems.isNotEmpty) {
        currentMainCard = vipCardItems.first;
        if (currentMainCard?.buyList != null && currentMainCard!.buyList!.isNotEmpty) {
          currentSubCard = currentMainCard!.buyList!.first;
        }
      }
      update();
      Tools.hideLoading();
    }).catchError((onError) {
      print(onError);
      Tools.hideLoading();
    });
  }

  ///获取个用户已有的权益卡
  Future getVipHaveCardListInfo() async {
    Tools.showLoading();
    var params = {'sid': AppData.sid};
    return Network.getVipHaveCardList(params).then((value) {
      infoEntity = HavelistInfoEntity.fromJson(value);
      vipCardItems = infoEntity?.card ?? [];
      if (vipCardItems.isNotEmpty) {
        currentMainCard = vipCardItems.first;
        if (currentMainCard?.buyList != null && currentMainCard!.buyList!.isNotEmpty) {
          currentSubCard = currentMainCard!.buyList!.first;
        }
      }
      update();
      Tools.hideLoading();
    }).catchError((onError) {
      print(onError);
      Tools.hideLoading();
    });
  }

  void changeIndex(int index) {
    currentIndex = index;
    if (index >= 0 && index < vipCardItems.length) {
      vipCardItems.asMap().forEach((i, element) {
        if (i == index) {
          currentMainCard = element;
        }
      });
    }
    refreshBuyList(index);
    update();
  }

  void refreshBuyList(int index) {
    var model = vipCardItems[index];
    buyList = model.buyList ?? [];
    selected = 0;
    select(selected);
  }

  ///选中哪张次卡
  void select(int index) {
    if (index >= 0 && index < buyList.length) {
      buyList.asMap().forEach((i, element) {
        element.isSelected = (i == index);
        if (i == index) {
          currentSubCard = element;
        }
      });
    }
    update();
  }

  void getUserInfo() {
    Tools.showLoading();
    Network.getUserInfo().then((value) {
      AppData.sid = value['sid'];
      GlobalData.sid = value['sid'];
      AppData.mid = value['mid'];
      AppData.uid = value['uid'];
      AppData.avatar = value['avatar'];
      AppData.nickname = value['nickname'];
      AppData.phoneNumber = value['mobile'];
      Tools.hideLoading();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  // 买
  void buy() {
    if (currentMainCard?.receiveType == 1) {
      vipBuyCardPlaceCardInfo();
    } else {
      receiveCard();
    }
  }

  // 直接领取卡
  void receiveCard() {
    var cardId = currentMainCard?.id.toString();
    if (cardId == null) {
      Tools.showToast('卡id不存在');
    }
    Network.getVipReceiveCard(cardId!).then((value) {
      update();
      Tools.hideLoading();
      Tools.showToast("领取成功");
    }).catchError((onError) {
      print(onError);
      Tools.hideLoading();
    });
  }

  void vipBuyCardPlaceCardInfo() {
    var params = {'cardId': currentMainCard!.id, 'cardType': currentSubCard!.type, 'sid': AppData.sid};
    Network.vipBuyCardPlaceCard(params).then((value) {
      Get.toNamed(
        '${Routes.cashier}/?sn=${value['sn']}&price=${value['priceOrder']}&isCard=${'true'}',
      );
    }).catchError((onError) {
      print(onError);
      Tools.hideLoading();
    });
  }

  @override
  void onClose() {
    EventMgr.off(EventType.refreshLogin);
    super.onClose();
  }
}
